import React, { useEffect, useState, useCallback, useRef } from 'react';
import { View, Text, SafeAreaView, TextInput, FlatList, TouchableOpacity, Alert, Image, ActivityIndicator, RefreshControl, Modal, Dimensions, Animated, ScrollView } from 'react-native';
import Header from '../../../components/Header';
import { Picker } from '@react-native-picker/picker';
import { queryAsnUninstall, confirmAsn, getBodyListByBusNum, getProductSkuList } from './api';
import { AsnUninstallRecord } from './types';
import { Toast } from '@ant-design/react-native';
import { styles } from './styles';
import xiala from '../../../assets/xiala.png';

interface AsnUninstallProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

const AsnUninstall: React.FC<AsnUninstallProps> = ({ onNavigateToLogin, onBackPress }) => {
    const [asnList, setAsnList] = useState<AsnUninstallRecord[]>([]);
    const [keyword, setKeyword] = useState('');
    const [loading, setLoading] = useState(false);

    // 分页相关状态
    const [current, setCurrent] = useState(1);
    const [size] = useState(10);
    const [hasMore, setHasMore] = useState(true);
    const [loadingMore, setLoadingMore] = useState(false);
    const [refreshing, setRefreshing] = useState(false);

    // 收起展开状态 - 改为管理每个物料项目的展开状态
    const [expandedItems, setExpandedItems] = useState<{ [key: string]: boolean }>({});



    // 图片预览状态
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');

    const [quantityModalVisible, setQuantityModalVisible] = useState(false);
    const [currentConfirmItem, setCurrentConfirmItem] = useState<AsnUninstallRecord | null>(null);
    const [uninstallQuantity, setUninstallQuantity] = useState('');
    const [confirmLoading, setConfirmLoading] = useState(false);

    const [addModalVisible, setAddModalVisible] = useState(false);
    const [addBusNum, setAddBusNum] = useState('');
    const [addProductList, setAddProductList] = useState<any[]>([]);
    const [addProductId, setAddProductId] = useState('');
    const [addSkuList, setAddSkuList] = useState<any[]>([]);
    const [addSkuId, setAddSkuId] = useState('');
    const [addQuantity, setAddQuantity] = useState('');
    const [addLoading, setAddLoading] = useState(false);

    const [productPickerVisible, setProductPickerVisible] = useState(false);
    const [skuPickerVisible, setSkuPickerVisible] = useState(false);
    const [productArrowRotation] = useState(new Animated.Value(0));
    const [skuArrowRotation] = useState(new Animated.Value(0));

    const addBusNumSearchTimeout = useRef<NodeJS.Timeout | null>(null);

    const handleAddBusNumChange = (text: string) => {
        setAddBusNum(text);
        setAddProductId('');
        setAddSkuId('');
        setAddProductList([]);
        setAddSkuList([]);
        if (addBusNumSearchTimeout.current) {
            clearTimeout(addBusNumSearchTimeout.current);
        }
        addBusNumSearchTimeout.current = setTimeout(async () => {
            if (text) {
                try {
                    console.log('getBodyListByBusNum 提交数据:', { bus_num: text });
                    const res = await getBodyListByBusNum(text);
                    console.log('getBodyListByBusNum 返回值:', res);
                    setAddProductList(res?.data || []);
                } catch (e) {
                    Toast.fail('获取产品失败');
                    setAddProductList([]);
                }
            }
        }, 400);
    };

    const fetchAsnData = async (searchKeyword?: string, isLoadMore: boolean = false) => {
        if (isLoadMore) {
            setLoadingMore(true);
        } else {
            setLoading(true);
            setCurrent(1);
            setHasMore(true);
        }

        try {
            const params = {
                current: isLoadMore ? current + 1 : 1,
                size,
                type: "WAIT_RECEIVE",
                ...(searchKeyword && { keyword: searchKeyword })
            };

            console.log('开始调用 queryAsn 接口...');
            const response = await queryAsnUninstall(params);
            console.log('queryAsn 接口调用成功');

            if (response.code === 200) {
                const newRecords = response.data.records || [];
                const total = response.data.total || 0;

                if (isLoadMore) {
                    setAsnList(prev => [...prev, ...newRecords]);
                    setCurrent(prev => prev + 1);
                } else {
                    setAsnList(newRecords);
                    setCurrent(1);
                }

                // 判断是否还有更多数据
                const totalLoaded = isLoadMore ? asnList.length + newRecords.length : newRecords.length;
                setHasMore(totalLoaded < total);
            }
        } catch (error) {
            console.error('queryAsn 接口调用失败:', error);
            if (!isLoadMore) {
                setAsnList([]);
            }
        } finally {
            if (isLoadMore) {
                setLoadingMore(false);
            } else {
                setLoading(false);
            }
        }
    };

    useEffect(() => {
        fetchAsnData();
    }, []);

    // 滑动到底部加载更多
    const handleLoadMore = () => {
        if (hasMore && !loadingMore && !loading) {
            fetchAsnData(keyword, true);
        }
    };

    // 下拉刷新
    const handleRefresh = async () => {
        setRefreshing(true);
        await fetchAsnData(keyword, false);
        setRefreshing(false);
    };

    // 防抖搜索函数
    const debouncedSearch = useCallback(
        (() => {
            let timeoutId: NodeJS.Timeout;
            return (searchKeyword: string) => {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                    fetchAsnData(searchKeyword, false);
                }, 500); // 500ms 延迟
            };
        })(),
        []
    );

    const handleSearch = () => {
        fetchAsnData(keyword, false);
    };

    const handleKeywordChange = (text: string) => {
        setKeyword(text);
        if (text.trim() === '') {
            // 如果搜索框为空，立即搜索所有数据
            fetchAsnData('', false);
        } else {
            // 否则使用防抖搜索
            debouncedSearch(text);
        }
    };



    const handleConfirmArrival = (item: AsnUninstallRecord) => {
        setCurrentConfirmItem(item);
        setUninstallQuantity('');
        setQuantityModalVisible(true);
    };

    const handleQuantityConfirm = async () => {
        if (!uninstallQuantity || isNaN(Number(uninstallQuantity)) || Number(uninstallQuantity) <= 0) {
            Toast.fail('请输入有效的到货数量');
            return;
        }
        if (!currentConfirmItem) return;
        setConfirmLoading(true);
        try {
            const params = {
                uninstall_quantity: uninstallQuantity,
                bus_num: currentConfirmItem.header_num || '',
                product_id: currentConfirmItem.product_id || '',
                sku_id: currentConfirmItem.sku_id || '',
            };
            const response = await confirmAsn(params);
            if (response.code === 200) {
                Toast.success(response.msg || '确认到货成功');
                // setQuantityModalVisible(false);
                fetchAsnData(keyword, false);
            } else {
                Toast.fail(response.msg || '确认到货失败');
            }
        } catch (error) {
            Toast.fail('确认到货失败，请重试');
        } finally {
            setConfirmLoading(false);
            setQuantityModalVisible(false);
        }
    };

    // 切换展开收起状态 - 改为管理每个物料项目
    const toggleExpand = (bodyId: string) => {
        setExpandedItems(prev => ({
            ...prev,
            [bodyId]: !prev[bodyId]
        }));
    };

    const handleAddPress = () => {
        setAddModalVisible(true);
        setAddBusNum('');
        setAddProductList([]);
        setAddProductId('');
        setAddSkuList([]);
        setAddSkuId('');
        setAddQuantity('');
    };

    const handleAddBusNumBlur = async () => {
        if (!addBusNum) return;
        try {
            const res = await getBodyListByBusNum(addBusNum);
            setAddProductList(res?.data || []);
            setAddProductId('');
            setAddSkuList([]);
            setAddSkuId('');
        } catch (e) {
            Toast.fail('获取产品失败');
            setAddProductList([]);
            setAddProductId('');
            setAddSkuList([]);
            setAddSkuId('');
        }
    };

    const handleAddProductChange = async (productId: string) => {
        setAddProductId(productId);
        setAddSkuId('');
        try {
            console.log('getProductSkuList 请求数据:', { product_id: productId });
            const res = await getProductSkuList(productId);
            console.log('getProductSkuList 返回值:', res);
            setAddSkuList(res?.data || []);
        } catch (e) {
            Toast.fail('获取SKU失败');
            setAddSkuList([]);
        }
    };

    const handleAddConfirm = async () => {
        console.log('bus_num:', addBusNum, 'product_id:', addProductId, '759475334755123200_ASN-202507240009:', addSkuId, 'quantity:', addQuantity);
        // if (!addBusNum || !addProductId || !addSkuId || !addQuantity) {
        //     Toast.fail('请填写完整信息');
        //     return;
        // }
        setAddLoading(true);
        try {
            const params = {
                uninstall_quantity: addQuantity,
                bus_num: addBusNum,
                product_id: addProductId,
                sku_id: addSkuId,
            };
            const res = await confirmAsn(params);
            if (res.code === 200) {
                Toast.success(res.msg || '确认到货成功');
                // setAddModalVisible(false);
                fetchAsnData(keyword, false);
            } else {
                Toast.fail(res.msg || '确认到货失败');
            }
        } catch (e) {
            Toast.fail('确认到货失败');
        } finally {
            setAddLoading(false);
            setAddModalVisible(false);
        }
    };

    // 产品选择器动画切换
    const toggleProductPicker = () => {
        const toValue = productPickerVisible ? 0 : 1;
        setProductPickerVisible(!productPickerVisible);
        Animated.timing(productArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };
    // SKU选择器动画切换
    const toggleSkuPicker = () => {
        const toValue = skuPickerVisible ? 0 : 1;
        setSkuPickerVisible(!skuPickerVisible);
        Animated.timing(skuArrowRotation, {
            toValue,
            duration: 200,
            useNativeDriver: true,
        }).start();
    };


    const renderAsnItem = ({ item }: { item: AsnUninstallRecord }) => {
        const isExpanded = expandedItems[item.id];

        return (
            <View style={styles.card}>
                <View style={styles.cardHeader}>
                    <View style={styles.headerRow}>
                        <Text style={styles.label}>单号</Text>
                        <Text style={styles.value}>{item.header_num}</Text>
                    </View>
                    <View style={styles.headerRow}>
                        <Text style={styles.label}>业务单号</Text>
                        <Text style={styles.value}>{item.odd_num || '-'}</Text>
                    </View>
                </View>
                <View style={styles.bodyItemHeader}>
                    <View style={styles.bodyItemLeft}>
                        <TouchableOpacity
                            onPress={() => {
                                setSelectedImage(item.product_link ? String(item.product_link) : '');
                                setImageModalVisible(true);
                            }}
                        >
                            <Image
                                source={item.product_link ? { uri: item.product_link } : require('../../../assets/zwtp.png')}
                                style={styles.productImage}
                                resizeMode="contain"
                            />
                        </TouchableOpacity>
                        <View style={styles.bodyItemInfo}>
                            <Text style={styles.bodyItemLabel}>物料编码</Text>
                            <Text style={styles.bodyItemValue}>{item.product_encode}</Text>
                            <Text style={styles.bodyItemLabel}>数量</Text>
                            <Text style={styles.bodyItemValue}>{item.arrival_quantity}</Text>
                        </View>
                    </View>
                </View>
                {/* 展开详情 */}
                {isExpanded && (
                    <View style={styles.expandedDetails}>
                        <View style={styles.detailsContent}>
                            <View style={styles.detailRow}>
                                <Text style={styles.detailLabel}>型号</Text>
                                <Text style={styles.detailValue}>: {item.product_model}</Text>
                            </View>
                            <View style={styles.detailRow}>
                                <Text style={styles.detailLabel}>物料规格</Text>
                                <Text style={styles.detailValue}>: {item.product_specs}</Text>
                            </View>
                            <View style={styles.detailRow}>
                                <Text style={styles.detailLabel}>计划时间</Text>
                                <Text style={styles.detailValue}>: {item.arrival_time}</Text>
                            </View>
                            <View style={styles.detailRow}>
                                <Text style={styles.detailLabel}>供应商</Text>
                                <Text style={styles.detailValue}>: {item.supplier_name}</Text>
                            </View>
                        </View>
                    </View>
                )}
                {/* 展开/收起按钮 */}
                <TouchableOpacity
                    style={styles.expandButton}
                    onPress={() => toggleExpand(item.id)}
                >
                    <Text style={styles.expandButtonText}>
                        {isExpanded ? '收起' : '展开'}
                    </Text>
                </TouchableOpacity>
                {/* 确认到货按钮 */}
                <View style={styles.bottomActions}>
                    <TouchableOpacity
                        style={styles.confirmButtonSmall}
                        onPress={() => handleConfirmArrival(item)}
                    >
                        <Text style={styles.confirmButtonTextSmall}>确认到货</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    };



    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="确认到货"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
                showAddButton={true}
                onAddPress={handleAddPress}
            />
            <View style={styles.content}>
                <View style={styles.searchContainer}>
                    <View style={styles.searchWrapper}>
                        <TextInput
                            style={styles.searchInput}
                            placeholder="请输入到货单号搜索"
                            placeholderTextColor="#999"
                            value={keyword}
                            onChangeText={handleKeywordChange}
                            returnKeyType="search"
                            autoFocus
                        />
                        {keyword.length > 0 && (
                            <TouchableOpacity
                                style={styles.clearButton}
                                onPress={() => {
                                    setKeyword('');
                                    fetchAsnData('', false);
                                }}
                            >
                                <Text style={styles.clearButtonText}>×</Text>
                            </TouchableOpacity>
                        )}
                    </View>
                </View>

                {loading ? (
                    <View style={styles.loadingContainer}>
                        <ActivityIndicator size="large" color="#007AFF" />
                        <Text style={styles.loadingText}>搜索中...</Text>
                    </View>
                ) : (
                    <FlatList
                        data={asnList}
                        renderItem={renderAsnItem}
                        keyExtractor={(item) => item.id}
                        contentContainerStyle={styles.listContainer}
                        showsVerticalScrollIndicator={false}
                        onEndReached={handleLoadMore}
                        onEndReachedThreshold={0.1}
                        refreshControl={
                            <RefreshControl
                                refreshing={refreshing}
                                onRefresh={handleRefresh}
                                colors={['#007AFF']}
                                tintColor="#007AFF"
                            />
                        }
                        ListEmptyComponent={
                            asnList.length === 0 ? (
                                <View style={styles.emptyContainer}>
                                    <Image
                                        source={require('../../../assets/zwsj.png')}
                                        style={styles.emptyImage}
                                        resizeMode="contain"
                                    />
                                    <Text style={styles.emptyText}>暂无数据</Text>
                                </View>
                            ) : null
                        }
                        ListFooterComponent={
                            loadingMore ? (
                                <View style={styles.loadingMoreContainer}>
                                    <ActivityIndicator size="small" color="#007AFF" />
                                    <Text style={styles.loadingMoreText}>加载更多...</Text>
                                </View>
                            ) : null
                        }
                    />
                )}
            </View>

            {/* 图片全屏显示模态框 */}
            <Modal visible={imageModalVisible} transparent={true} animationType="fade">
                <View style={styles.imageModalContainer}>
                    <TouchableOpacity
                        style={styles.imageModalOverlay}
                        onPress={() => setImageModalVisible(false)}
                    >
                        <Image
                            source={selectedImage ? { uri: selectedImage } : require('../../../assets/zwtp.png')}
                            style={styles.fullScreenImage}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                </View>
            </Modal>

            <Modal visible={quantityModalVisible} transparent animationType="fade">
                <View style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.4)', justifyContent: 'center', alignItems: 'center' }}>
                    <View style={{ backgroundColor: '#fff', borderRadius: 8, paddingTop: 24, paddingHorizontal: 24, width: 320 }}>
                        {/* 标题 */}
                        <Text style={{ fontSize: 18, fontWeight: 'bold', textAlign: 'center', marginBottom: 10 }}>确认到货</Text>
                        {/* 内容部分可滚动，最大高度 400 */}
                        <ScrollView
                            style={{ maxHeight: 400 }}
                            contentContainerStyle={{ paddingBottom: 10 }}
                            showsVerticalScrollIndicator={false}
                        >
                            <Text style={{ fontSize: 16, marginBottom: 8 }}>到货数量</Text>
                            <TextInput
                                style={styles.faultInput}
                                placeholder="请输入到货数量"
                                placeholderTextColor="#999"
                                keyboardType="numeric"
                                value={uninstallQuantity}
                                onChangeText={setUninstallQuantity}
                                editable={!confirmLoading}
                            />
                        </ScrollView>
                        {/* 按钮区域，固定在底部 */}
                        <View style={[styles.modalButtonContainer, { backgroundColor: '#fff', paddingBottom: 10 }]}>
                            <TouchableOpacity style={styles.cancelButton} onPress={() => !confirmLoading && setQuantityModalVisible(false)}>
                                <Text style={styles.cancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.confirmButton} onPress={handleQuantityConfirm} disabled={confirmLoading}>
                                <Text style={styles.confirmButtonText}>{confirmLoading ? '提交中...' : '确认'}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>

            <Modal visible={addModalVisible} animationType="fade" transparent={true}>
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <View style={styles.modalHeader}>
                            <Text style={styles.modalTitle}>到货</Text>
                        </View>

                        <ScrollView style={styles.modalBody} showsVerticalScrollIndicator={false}>
                            {/* 到货单号输入 */}
                            <Text style={{ marginBottom: 6 }}>请输入到货单号</Text>
                            <View style={styles.modalSearchWrapper}>
                                <TextInput
                                    style={styles.scanInput}
                                    placeholder="到货单号"
                                    placeholderTextColor="#999"
                                    value={addBusNum}
                                    onChangeText={handleAddBusNumChange}
                                    editable={!addLoading}
                                    autoFocus
                                />
                                {addBusNum.length > 0 && (
                                    <TouchableOpacity
                                        style={styles.modalClearButton}
                                        onPress={() => setAddBusNum('')}
                                    >
                                        <Text style={styles.modalClearButtonText}>×</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                            {/* 产品选择器 - 下拉样式 */}
                            <View style={styles.levelContainer}>
                                <Text style={styles.levelLabel}>产品</Text>
                                <TouchableOpacity style={styles.levelSelector} onPress={toggleProductPicker}>
                                    <Text style={styles.levelText}>
                                        {addProductList.find(p => p.product_id === addProductId)?.product_name || '请选择产品'}
                                    </Text>
                                    <Animated.Image
                                        source={xiala}
                                        style={[styles.arrowIcon, {
                                            transform: [{
                                                rotate: productArrowRotation.interpolate({
                                                    inputRange: [0, 1],
                                                    outputRange: ['0deg', '180deg']
                                                })
                                            }]
                                        }]}
                                    />
                                </TouchableOpacity>
                                {productPickerVisible && (
                                    <View style={styles.modalLevelDropdown}>
                                        {addProductList.map(option => (
                                            <TouchableOpacity
                                                key={option.product_id}
                                                style={styles.modalLevelOption}
                                                onPress={() => {
                                                    setProductPickerVisible(false);
                                                    Animated.timing(productArrowRotation, {
                                                        toValue: 0,
                                                        duration: 200,
                                                        useNativeDriver: true,
                                                    }).start();
                                                    handleAddProductChange(option.product_id);
                                                }}
                                            >
                                                <Text style={styles.modalLevelOptionText}>{option.product_name}</Text>
                                            </TouchableOpacity>
                                        ))}
                                    </View>
                                )}
                            </View>
                            {/* SKU选择器 - 下拉样式 */}
                            <View style={styles.levelContainer}>
                                <Text style={styles.levelLabel}>SKU</Text>
                                <TouchableOpacity style={styles.levelSelector} onPress={toggleSkuPicker}>
                                    <Text style={styles.levelText}>
                                        {addSkuList.find(sku => sku.id === addSkuId)?.sku || '请选择SKU'}
                                    </Text>
                                    <Animated.Image
                                        source={xiala}
                                        style={[styles.arrowIcon, {
                                            transform: [{
                                                rotate: skuArrowRotation.interpolate({
                                                    inputRange: [0, 1],
                                                    outputRange: ['0deg', '180deg']
                                                })
                                            }]
                                        }]}
                                    />
                                </TouchableOpacity>
                                {skuPickerVisible && (
                                    <View style={styles.modalLevelDropdown}>
                                        {addSkuList.map(option => (
                                            <TouchableOpacity
                                                key={option.id}
                                                style={styles.modalLevelOption}
                                                onPress={() => {
                                                    setSkuPickerVisible(false);
                                                    Animated.timing(skuArrowRotation, {
                                                        toValue: 0,
                                                        duration: 200,
                                                        useNativeDriver: true,
                                                    }).start();
                                                    setAddSkuId(option.id);
                                                }}
                                            >
                                                <Text style={styles.modalLevelOptionText}>{option.sku}</Text>
                                            </TouchableOpacity>
                                        ))}
                                    </View>
                                )}
                            </View>
                            {/* 到货数量输入 */}
                            <View style={styles.faultContainer}>
                                <Text style={styles.faultLabel}>到货数量</Text>
                                <TextInput
                                    style={styles.faultInput}
                                    placeholder="请输入到货数量"
                                    placeholderTextColor="#999"
                                    keyboardType="numeric"
                                    value={addQuantity}
                                    onChangeText={setAddQuantity}
                                    editable={!addLoading}
                                />
                            </View>
                        </ScrollView>

                        {/* 按钮区域 */}
                        <View style={styles.modalButtonContainer}>
                            <TouchableOpacity style={styles.cancelButton} onPress={() => !addLoading && setAddModalVisible(false)}>
                                <Text style={styles.cancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.confirmButton} onPress={handleAddConfirm} disabled={addLoading}>
                                <Text style={styles.confirmButtonText}>{addLoading ? '提交中...' : '确定'}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        </SafeAreaView>
    );
};

export default AsnUninstall; 